package com.bocomm.tracevisualization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bocomm.tracevisualization.api.entity.TraceTargetData;
import com.bocomm.tracevisualization.api.service.ITraceTargetDataService;
import com.bocomm.tracevisualization.api.service.ITranslateManagementService;
import com.bocomm.tracevisualization.api.vo.req.BrokenLineReq;
import com.bocomm.tracevisualization.api.vo.resp.BrokenLineGraph;
import com.bocomm.tracevisualization.api.vo.resp.BrokenLinePoint;
import com.bocomm.tracevisualization.mapper.TraceTargetDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

import static com.bocomm.tracevisualization.core.CmdExecutor.fetchLocalHostIp;

/**
 * <p>
 * 每次traceroute请求的结果数据 服务实现类
 * </p>
 *
 * @author cxp
 * @since 2024-03-20
 */
@Service
public class TraceTargetDataServiceImpl extends ServiceImpl<TraceTargetDataMapper, TraceTargetData> implements ITraceTargetDataService {


    @Autowired
    ITranslateManagementService translateManagementService;

    /**
     * 折线图
     *
     * @param req
     * @return
     */
    @Override
    public BrokenLineGraph brokenLine(BrokenLineReq req) {
        String targetIp = req.getTargetIp();
        String sourceIp = fetchLocalHostIp();
        QueryWrapper<TraceTargetData> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<TraceTargetData> last = queryWrapper.lambda()
                .eq(TraceTargetData::getTargetIp, targetIp)
                .eq(StringUtils.hasText(sourceIp), TraceTargetData::getSourceIp, sourceIp)
                .orderByDesc(TraceTargetData::getTraceTime)
                .last("limit 120");
        List<TraceTargetData> traceTargetData = baseMapper.selectList(last);
        List<BrokenLinePoint> points = traceTargetData.stream().map(BrokenLinePoint::new).collect(Collectors.toList());
        String targetHostName = translateManagementService.aliasIp(targetIp);
        String sourceHostName = translateManagementService.aliasIp(sourceIp);

        return new BrokenLineGraph( sourceIp,sourceHostName,targetIp,targetHostName,points);
    }


}
